package com.tiku.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tiku.common.ResultJson;
import com.tiku.controller.DTO.CommentDTO;
import com.tiku.controller.DTO.CommentTreeDTO;
import com.tiku.controller.DTO.UserCommentDTO;
import com.tiku.controller.TO.replyCommentTO;
import com.tiku.entity.UserComment;
import com.tiku.mapper.UserCommentMapper;
import com.tiku.service.UserCommentService;
import com.tiku.utils.RedisCache;
import com.tiku.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundSetOperations;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * @author Administrator
 * @description 针对表【user_comment】的数据库操作Service实现
 * @createDate 2024-09-21 20:45:12
 */
@Service
public class UserCommentServiceImpl extends ServiceImpl<UserCommentMapper, UserComment>
        implements UserCommentService {

    @Autowired
    private UserCommentMapper userCommentMapper;

    @Autowired
    private RedisCache redisCache;

    //    查询全部评论用户信息
    @Override
    public ResultJson getUserCommentList(Integer pageNum, String classificationType) {
        pageNum=(pageNum-1)*10;
        List<UserCommentDTO> Comments = userCommentMapper.selectUserComment(pageNum, classificationType);

        for (UserCommentDTO comment : Comments) {
            long likeCount = getLikeCount(comment.getId());
            boolean b = hasUserLiked(comment.getId(), ThreadLocalUtil.getThreadLocal());
            Long aLong = userCommentMapper.selectCount(new LambdaQueryWrapper<UserComment>().eq(UserComment::getPId, comment.getId()));
            comment.setCommentsCount(aLong);
            comment.setLiked(b);
            comment.setThumbsUpCount(likeCount);
        }
        return ResultJson.success(Comments);
    }

    @Override
    public ResultJson getSelectUserComment(String id) {

        //一级评论
        UserCommentDTO selectedUserComment = userCommentMapper.getSelectedUserComment(id);
        //二级评论
        List<CommentTreeDTO> commentTreeDTO = userCommentMapper.selectSonComments(id);
        //三级评论
        for (CommentTreeDTO treeDTO : commentTreeDTO) {
            String id1 = treeDTO.getId();
            List<CommentTreeDTO> commentTreeDTOS = userCommentMapper.selectSonComments(id1);
            treeDTO.setComments(commentTreeDTOS);
        }
        CommentDTO commentDTO = new CommentDTO();
        commentDTO.setUserCommentDTO(selectedUserComment);
        //设置当前评论有多少点赞评论
        long likeCount = getLikeCount(id);
        selectedUserComment.setThumbsUpCount(likeCount);
        //获取当前用户是否已经点赞
        boolean b = hasUserLiked(id, ThreadLocalUtil.getThreadLocal());
        selectedUserComment.setLiked(b);
        //获取评论数量
        Long aLong = userCommentMapper.selectCount(new LambdaQueryWrapper<UserComment>().eq(UserComment::getPId, id));
        selectedUserComment.setCommentsCount(aLong);

        commentDTO.setCommentTreeDTO(commentTreeDTO);

        return ResultJson.success(commentDTO);
    }

    @Override
    public ResultJson addComment(UserComment userComment) {
        if (StringUtils.isEmpty(userComment.getComment())) {
            return ResultJson.error("评论不能为空!");
        }
        String threadLocal = ThreadLocalUtil.getThreadLocal();
        userComment.setId(null);
        userComment.setPId("0");
        userComment.setUserId(threadLocal);
        userComment.setCreateTime(new Date());
        int insert = userCommentMapper.insert(userComment);
        return insert > 0 ? ResultJson.success(null) : ResultJson.sysError();
    }
    @Override
    public ResultJson replyComment(replyCommentTO replyCommentTO) {

        if (StringUtils.isEmpty(replyCommentTO.getComment())|| replyCommentTO.getComment().trim().equals("")) {
            return ResultJson.error("评论不能为空!");
        }
        String userId = ThreadLocalUtil.getThreadLocal();
        UserComment userComment =new UserComment();
        userComment.setComment(replyCommentTO.getComment());
        userComment.setUserId(userId);

        String replyId = replyCommentTO.getReplyId();
        UserComment replyInfo = userCommentMapper.selectById(replyId);
        if (Objects.isNull(replyInfo)){
            return ResultJson.error("该评论不存在!");
        }

        userComment.setPId(replyId);
        userComment.setCreateTime(new Date());
        userComment.setCommentType("1");
        int insert = userCommentMapper.insert(userComment);

        return insert>0? ResultJson.success() : ResultJson.sysError();
    }


    @Override
    public ResultJson thumbsUp(String id) {
        boolean b1 = hasUserLiked(id, ThreadLocalUtil.getThreadLocal());
        boolean b ;
        if (b1) {
            //已经点赞 进行取消
            b = unlikeComment(id, ThreadLocalUtil.getThreadLocal());
            return b ? ResultJson.success("取消成功") : ResultJson.sysError();
        } else {
            //没有点赞  进行点赞
            b = likeComment(id, ThreadLocalUtil.getThreadLocal());
            return b ? ResultJson.success("点赞成功") : ResultJson.sysError();
        }


    }


    // 点赞功能：用户对指定评论进行点赞
    public boolean likeComment(String commentId, String userId) {
        // Redis 中使用 Set 来存储每个评论的点赞用户 ID
        String key = "comment:likes:" + commentId; // 例如 comment:likes:12345

        Set<String> userSet = new HashSet<>();
        userSet.add(userId);  // 将 userId 添加到集合中
        redisCache.setCacheSet(key, userSet);// 使用可变的 HashSet
        return true;
    }

    // 取消点赞功能：用户取消对指定评论的点赞
    public boolean unlikeComment(String commentId, String userId) {
        // Redis 中使用 Set 来存储每个评论的点赞用户 ID
        String key = "comment:likes:" + commentId; // 例如 comment:likes:12345

        // 从 Set 中移除用户 ID
        Set<Object> cacheSet = redisCache.getCacheSet(key);
        cacheSet.remove(userId);
        redisCache.setCacheSet(key, cacheSet).remove(userId);
        return true;
    }

    // 获取评论的点赞数
    public long getLikeCount(String commentId) {
        // Redis 中使用 Set 来存储每个评论的点赞用户 ID
        String key = "comment:likes:" + commentId; // 例如 comment:likes:12345

        // 获取 Set 的大小，即评论的点赞数
        Set<String> likes = redisCache.getCacheSet(key);
        return likes != null ? likes.size() : 0;
    }

    // 检查用户是否已点赞某评论
    public boolean hasUserLiked(String commentId, String userId) {
        String key = "comment:likes:" + commentId; // 例如 comment:likes:12345
        Set<String> likes = redisCache.getCacheSet(key);
        return likes != null && likes.contains(userId);
    }
}




